using System;
using System.Collections;
using System.Globalization;
using WPFTemplateLib.WpfConverters.Core;

namespace WPFTemplateLib.WpfConverters
{
	/// <summary>
	/// [转换器] 是否是列表的头或尾元素
	/// </summary>
	/// <remarks>
	/// 绑定和参数：绑定某个对象，参数传该对象所在的列表(<see cref="IList"/>类型) <para/>
	/// 返回规则：列表类型不对或者为空则返回 false，否则依据属性 <see cref="HeadOrTail"/> 结合实际情况返回对象是否在列表的头或尾。
	/// </remarks>
	public class IsHeadOrTailOfListConverter : ValueConverterBase
    {
		/// <summary>
		/// 需要判断的是头还是尾（头-true，[默认]尾-false）
		/// </summary>
		public bool HeadOrTail { get; set; }

		/// <inheritdoc />
		public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			try
			{
				if(parameter is not IList list)
					return false;

				int listLen = list.Count;
				if(listLen == 0)
					return false;

				bool isHeadOrTailOfList = false;
				if(HeadOrTail)
				{
					if(list[0] == value)
						isHeadOrTailOfList = true;
				}
				else
				{
					if(list[listLen - 1] == value)
						isHeadOrTailOfList = true;
				}

				return isHeadOrTailOfList;
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex);
				return false;
			}
		}

		/// <inheritdoc />
		public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}
}
